package com.stdz.counter.service.impl;

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.Page;
import com.stdz.counter.constant.MeterConstant;
import com.stdz.counter.dao.*;
import com.stdz.counter.entity.*;
import com.stdz.counter.service.DeviceService;
import com.stdz.counter.service.MeterTaskService;
import com.stdz.counter.service.SerialPortService;
import com.stdz.counter.task.CronTaskRegistrar;
import com.stdz.counter.utils.ConversionUtil;
import com.stdz.counter.utils.DateUtils;
import com.stdz.counter.utils.MeterValueUtil;
import com.stdz.counter.utils.SchedulingRunnable;
import de.re.easymodbus.exceptions.ModbusException;
import de.re.easymodbus.modbusclient.ModbusClient;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

/**
 * @author peanut
 */
@Service
@Slf4j
public class DeviceServiceImpl implements DeviceService {

    private static final Logger LOG = LoggerFactory.getLogger(SchedulingRunnable.class);

    @Autowired
    MeterDao meterDao;

    @Autowired
    ModbusTypeDao modbusTypeDao;

    @Autowired
    SerialPortService serialPortService;

    @Autowired
    MeterTaskDao meterTaskDao;

    @Autowired
    DeviceService deviceService;

    @Autowired
    CronTaskRegistrar taskRegistrar;

    @Autowired
    MeterTaskService meterTaskService;

    @Autowired
    MeterRecordDao meterRecordDao;

    @Autowired
    MeterMDao meterMDao;

    @Autowired
    MeterHDao meterHDao;

    @Autowired
    MeterDDao meterDDao;

    @Autowired
    MeterYDao meterYDao;

    @Override
    public Boolean addDevice(Map map) throws Exception {
        // 添加通讯接口和仪表
        return this.addModbusType(map);
    }

    @Override
    public Boolean restartSerialPort(String serialPort){
        try {
            serialPortService.readSerialPortIdData(serialPort);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    @Override
    public Page<Meter> findAllCounters() {
        return meterDao.findAll();
    }

    @Override
    public List<String> findAllPorts() {
        return modbusTypeDao.findSerialPorts();
    }

    @Override
    public void suspend(String com, int id) throws Exception {

        ModbusClient modbusClient = MeterConstant.modbusClientMap.get(com);
        modbusClient.setUnitIdentifier((byte)id);
        modbusClient.WriteSingleRegister(0, 4);
    }

    @Override
    public Map findById(Long id) {
        return meterDao.findById(id);
    }

    @Override
    public void clear(String port, int ip, String clearMode, String flag) throws Exception {
        ModbusClient modbusClient = MeterConstant.modbusClientMap.get(port);
        modbusClient.setSerialFlag(true);
        modbusClient.setUnitIdentifier((byte)ip);
        // 是否开启双清零模式
        if (MeterConstant.CLEAR_MODE2.equals(clearMode)) {
            if (String.valueOf(MeterConstant.BCD_REGISTER_ADDRESS).equals(flag)) {
                LOG.debug("当前的串口是：{}" , port);
                LOG.debug("当前串口是否连接：{}" , modbusClient.isConnected());
                try {
                    modbusClient.WriteSingleRegister(0, 2);
                } catch (ModbusException e){
                    LOG.debug("clear...... modbus异常");
                    LOG.debug(e.getMessage());
                    e.printStackTrace();
                } catch (Exception e){
                    LOG.debug("clear...... Exception异常");
                    LOG.debug(e.getMessage());
                    e.printStackTrace();
                }
                LOG.debug("请求发送成功");
            }
        } else {
            if (String.valueOf(MeterConstant.BCD_REGISTER_ADDRESS).equals(flag)) {
                modbusClient.WriteSingleRegister(0, 1);
            } else {
                modbusClient.WriteSingleRegister(0, 2);
            }
        }
    }

    @Override
    public void delete(Long id) {

        // 获取到相关的modbus_id
        Map<String, Object> map = meterDao.findById(id);
        // 删除仪表
        meterDao.delete(id);
        // 删除数据库中的定时信息
        meterTaskDao.delete(Integer.valueOf(id + ""));
        // 删除线程池中的定时任务
        taskRegistrar.removeCronTask(Integer.valueOf(id + ""));

        // 删除通讯接口
        modbusTypeDao.delete(Integer.valueOf(map.get("modbusId").toString()));



    }

    @Override
    public void setCounter(Map map) throws IOException, ModbusException {

        // 获取到仪表id
        Integer id = Integer.valueOf(map.get("id").toString());

        // 先删除定时器
        meterTaskDao.delete(id);
        // 添加定时器
        MeterTask meterTask = new MeterTask();
        meterTask.setMeterId(id);
        if (MeterConstant.BIT_ZERO_FLAG.equals(map.get("type").toString())) {
            meterTask.setCron(DateUtils.formatDateByPattern(DateUtils.getDate(map.get("cron").toString())));
        } else {
            meterTask.setCron(DateUtils.getCron(map.get("cron").toString()));
        }

        meterTask.setType(map.get("type").toString());
        meterTask.setIsSuccess(false);
        meterTaskDao.addMeterTask(meterTask);

        // 修改定时器（先删除 再添加）
        // 判断当前仪表是否存在定时器  如果存在的话  修改  不存在的话 添加
        SchedulingRunnable task = new SchedulingRunnable(meterTask.getCron(), meterTask.getMeterId(), meterTaskService, deviceService);
        taskRegistrar.addCronTask(meterTask.getMeterId(), task, meterTask.getCron());

        Map<String, Object> data = meterDao.findById(Long.parseLong(id + ""));
        ModbusClient modbusClient = MeterConstant.modbusClientMap.get(data.get("port"));
        modbusClient.setUnitIdentifier((byte)Integer.parseInt(data.get("ip").toString()));
        String whetherBCD = data.get("whetherBCD").toString();
        int[] registerAddress = new int[4];
        int[] scalRegisterAddress = new int[2];
        String al1 = map.get("al1").toString();
        String al2 = map.get("al2").toString();
        String scal = map.get("scal").toString();
        if (data.containsKey("whetherBCD") && !StringUtils.isEmpty(whetherBCD) ) {
            if (MeterConstant.BIT_ONE_FLAG.equals(whetherBCD)) {
                try {
                    registerAddress = MeterValueUtil.getRegisterAddress(al1, al2);
                    modbusClient.WriteMultipleRegisters(MeterConstant.BCD_METER_ALARM, registerAddress);

                    BigDecimal scalVal = new BigDecimal(scal);
                    String coverScal = scalVal.multiply(new BigDecimal(DateUtils.getSecond(100))).stripTrailingZeros().toPlainString();
                    scalRegisterAddress = MeterValueUtil.getScalRegisterAddress(coverScal);
                    // 修改计数倍数
                    modbusClient.WriteMultipleRegisters(MeterConstant.BCD_SCAL, scalRegisterAddress);
                } catch (ModbusException e) {
                    throw new ModbusException("请检查你的串口链接和仪表信息");
                } catch (Exception e) {
                    throw new IOException("服务端异常");
                }
            } else {
                String al1Hex = ConversionUtil.toTenAdecimal(al1);
                String al2Hex = ConversionUtil.toTenAdecimal(al2);

                registerAddress = MeterValueUtil.getRegisterAddress(al1Hex, al2Hex);

                String val = new BigDecimal(scal).multiply(new BigDecimal(DateUtils.getSecond(10))).stripTrailingZeros().toPlainString();

                String scalHex = ConversionUtil.toTenAdecimal(val);

                scalRegisterAddress = MeterValueUtil.getScalRegisterAddress(scalHex);

                try {
                    // 修改计数倍数
                    modbusClient.WriteMultipleRegisters(MeterConstant.INT_SCAL, scalRegisterAddress);
                    // 修改报警值
                    modbusClient.WriteMultipleRegisters(MeterConstant.INT_METER_ALARM, registerAddress);
                } catch (Exception e ) {
                    throw new ModbusException("请检查你的串口链接和仪表信息");
                }
            }
        }

        // 设置寄存器
        String  meterAddress = map.get("registerAddress").toString();
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        params.put("al1", al1);
        params.put("al2", al2);
        params.put("scal", scal);
        params.put("upperRowInt", map.get("upperRowInt").toString());
        params.put("registerAddress", Integer.parseInt(meterAddress, 16) + "");
        meterDao.setCounter(params);

        // 修改全局map
        String port = data.get("port").toString();
        List<MeterModbus> singleSerialPortList = modbusTypeDao.findAllLinkModbusType(port);
        MeterConstant.serialPortMapCache.put(port, singleSerialPortList);
    }

    @Override
    public List<String> findAllComs() {
        return modbusTypeDao.findAllComs();
    }

    @Override
    public List<Map<String, Object>> findAllModbusType() {
        return modbusTypeDao.findAllModbusType();
    }

    @Transactional
    public Boolean addModbusType(Map map) throws Exception{
        // 添加通讯接口
        ModbusType modbusType = new ModbusType();
        modbusType.setCreateTime(DateUtil.date());
        modbusType.setUpdateTime(DateUtil.date());
        modbusType.setType(map.containsKey("type") ? Integer.valueOf(map.get("type").toString()) : MeterConstant.ERROR_PARAM_INT);
        modbusType.setPort(map.containsKey("port") ? map.get("port").toString() : MeterConstant.ERROR_PARAM_STR);
        modbusType.setBaudRate(map.containsKey("baudRate") ? map.get("baudRate").toString() : "9600");
            modbusType.setIp(map.containsKey("ip") ? map.get("ip").toString() : MeterConstant.ERROR_PARAM_STR);
        modbusTypeDao.addModbus(modbusType);
        map.put("modbusId", modbusType.getId());

        // 添加仪表
        this.addMeter(map);

        // 去读取计数器数值
        serialPortService.readSerialPortIdData(map.get("port").toString());
        return true;
    }

    public void addMeter(Map map) {
        Meter meter = new Meter();
        meter.setSuspend("0");
        meter.setModbusId(map.containsKey("modbusId") ? Long.valueOf(map.get("modbusId").toString()) : MeterConstant.ERROR_PARAM_INT);
        meter.setName(map.containsKey("name") ? map.get("name").toString() : MeterConstant.ERROR_PARAM_STR);
        meter.setUpperRow("0");
        meter.setLowerRow("0");
        meter.setUpperRowInt("1");
        meter.setWhetherBCD(map.containsKey("whetherBCD") ?  map.get("whetherBCD").toString() : MeterConstant.BIT_ONE_FLAG);
        meter.setAl1(MeterConstant.BIT_ZERO_FLAG);
        meter.setAl2(MeterConstant.BIT_ZERO_FLAG);
        meter.setTime(map.get("time").toString());
        meter.setClearMode(map.get("clearMode").toString());
        meter.setRegisterAddress(map.get("registerAddress").toString());
        meter.setOffLine(MeterConstant.BIT_ONE_FLAG);
        meterDao.addMeter(meter);
    }

    @Override
    public void clear(String id) throws Exception {
        Map meterMap =  deviceService.findById(Long.valueOf(id));
        deviceService.clear(meterMap.get("port").toString(),
                Integer.parseInt(meterMap.get("ip").toString()), meterMap.get("clearMode").toString(), MeterConstant.BIT_ONE_FLAG);
    }

    @Override
    public List<CurveData> findByDate(String type, String date, String meterIds) throws ParseException {
        List<MeterRecord> meterRecords = new ArrayList<>();
        List<CurveData> list = new ArrayList<>();
        String endTime = null;
        String[] meterIdClt = meterIds.split(",");
        switch (type){
            case "1":
                // 后一个小时
                endTime = DateUtils.formatDateLastHour(DateUtils.getLaterHour(date));
                for (String meterId : meterIdClt) {
                    CurveData curveData = new CurveData();
                    // al1的数组
                    List<BigDecimal> als = new ArrayList<>();
                    List<String> times = new ArrayList<>();
                    Map map = meterDao.findById(Long.valueOf(meterId));
                    meterRecords = meterMDao.findByDate(DateUtils.formatDateLastHour(DateUtils.getNowYMDH(date)), endTime,  Integer.valueOf(meterId));
                    if (meterRecords.size() > 0) {
                        for (int i = 0; i < meterRecords.size(); i++ ) {
                            MeterRecord meterRecord = meterRecords.get(i);
                            curveData.setName(map.get("name").toString());
                            if (meterRecord == null || StringUtils.isEmpty(meterRecord.getUpperRow())) {
                                if (i == 0) {
                                    als.add(BigDecimal.ZERO);
                                } else {
                                    als.add(als.get(i - 1));
                                }
                            } else {
                                als.add(new BigDecimal(meterRecord.getUpperRow()));
                            }
                        }
//                        curveData.setData(als);
                        curveData.setAreaStyle("");
                        curveData.setStack("个数");
                        curveData.setType("line");
                        list.add(curveData);
                    }
                }
                break;
            case "2":
                // 后一天
                endTime = DateUtils.formatDateLastDay(DateUtils.getLaterDay(date));
                for (String meterId : meterIdClt) {
                    CurveData curveData = new CurveData();
                    // al1的数组
                    List<BigDecimal> als = new ArrayList<>();
                    Map map = meterDao.findById(Long.valueOf(meterId));
                    meterRecords = meterHDao.findByDate(DateUtils.formatDateLastDay(DateUtils.getNowYMD(date)), endTime, Integer.valueOf(meterId));
                    if (meterRecords.size() > 0) {
                        for (int i = 0; i < meterRecords.size(); i++ ) {
                            MeterRecord meterRecord = meterRecords.get(i);
                            curveData.setName(map.get("name").toString());
                            if (meterRecord == null || StringUtils.isEmpty(meterRecord.getUpperRow())) {
                                if (i == 0) {
                                    als.add(BigDecimal.ZERO);
                                } else {
                                    als.add(als.get(i - 1));
                                }
                            } else {
                                als.add(new BigDecimal(meterRecord.getUpperRow()));
                            }
                        }
//                        curveData.setData(als);
                        curveData.setAreaStyle("");
                        curveData.setStack("个数");
                        curveData.setType("line");
                        list.add(curveData);
                    }
                }

                break;
            case "3":
                // 后一月
                String[] dateStr = date.split("-");
                String year = dateStr[0];
                String laterMonth = "";
                if (dateStr.equals("12")) {
                    laterMonth = "01";
                    year  = String.valueOf(Integer.valueOf(year) + 1);
                } else {
                    laterMonth = String.valueOf(Integer.valueOf(dateStr[1]) + 1);
                }

                for (String meterId : meterIdClt) {
                    CurveData curveData = new CurveData();
                    // al1的数组
                    List<BigDecimal> als = new ArrayList<>();
                    List<String> times = new ArrayList<>();
                    Map map = meterDao.findById(Long.valueOf(meterId));
                    if (laterMonth.length() < 2) {
                        laterMonth = "0" + laterMonth;
                    }
                    meterRecords = meterDDao.findByDate(date + "-01 00:00:00", date + "-31 00:00:00", Integer.valueOf(meterId));
                    if (meterRecords.size() > 0) {
                        for (int i = 0; i < meterRecords.size(); i++ ) {
                            MeterRecord meterRecord = meterRecords.get(i);
                            curveData.setName(map.get("name").toString());
                            if (meterRecord == null || StringUtils.isEmpty(meterRecord.getUpperRow())) {
                                if (i == 0) {
                                    als.add(BigDecimal.ZERO);
                                } else {
                                    als.add(als.get(i - 1));
                                }
                            } else {
                                als.add(new BigDecimal(meterRecord.getUpperRow()));
                            }
                        }
//                        curveData.setData(als);
                        curveData.setAreaStyle("");
                        curveData.setStack("个数");
                        curveData.setType("line");
                        list.add(curveData);
                    }
                }
                break;
            case "4":
                // 后一年
                for (String meterId : meterIdClt) {
                    CurveData curveData = new CurveData();
                    // al1的数组
                    List<BigDecimal> als = new ArrayList<>();
                    List<String> times = new ArrayList<>();
                    Map map = meterDao.findById(Long.valueOf(meterId));
                    meterRecords = meterYDao.findByDate(date + "-01-01 00:00:00",Integer.valueOf(date) + 1 + "" + "-01-01 00:00:00", Integer.valueOf(meterId));
                    if (meterRecords.size() > 0) {
                        for (int i = 0; i < meterRecords.size(); i++ ) {
                            MeterRecord meterRecord = meterRecords.get(i);
                            curveData.setName(map.get("name").toString());
                            if (meterRecord == null || StringUtils.isEmpty(meterRecord.getUpperRow())) {
                                if (i == 0) {
                                    als.add(BigDecimal.ZERO);
                                } else {
                                    als.add(als.get(i - 1));
                                }
                            } else {
                                als.add(new BigDecimal(meterRecord.getUpperRow()));
                            }
                        }
//                        curveData.setData(als);
                        curveData.setAreaStyle("");
                        curveData.setStack("个数");
                        curveData.setType("line");
                        list.add(curveData);
                    }
                }
                break;
            default:
                // 前一分钟(获取年月日时分)
                // 后一分钟
                endTime = DateUtils.formatDateLastTime(DateUtils.getLaterMinute(date));

                for (String meterId : meterIdClt) {
                    CurveData curveData = new CurveData();
                    // al1的数组
                    List<BigDecimal> als = new ArrayList<>();

                    Map map = meterDao.findById(Long.valueOf(meterId));
                    meterRecords = meterRecordDao.findByDate(date, endTime, Integer.valueOf(meterId));

                    if (meterRecords.size() > 0) {
                        for (int i = 0; i < meterRecords.size(); i++ ) {
                            MeterRecord meterRecord = meterRecords.get(i);
                            curveData.setName(map.get("name").toString());
                            if (meterRecord == null || StringUtils.isEmpty(meterRecord.getUpperRow())) {
                                if (i == 0) {
                                    als.add(BigDecimal.ZERO);
                                } else {
                                    als.add(als.get(i - 1));
                                }
                            } else {
                                als.add(new BigDecimal(meterRecord.getUpperRow()));
                            }
                        }
//                        curveData.setData(als);
//                        curveData.setAreaStyle("");
                        curveData.setStack("个数");
                        curveData.setType("line");
                        list.add(curveData);
                    }
                }
                break;
        }
        return list;
    }

    @Override
    public List<ColumnarData> findColumnChartByDate(String type, String date, String meterIds) throws ParseException {
        List<MeterRecord> meterRecords = new ArrayList<>();
        List<ColumnarData> list = new ArrayList<>();
        String endTime = null;
        String[] meterIdClt = meterIds.split(",");
        switch (type){
            case "1":
                // 后一个小时
                endTime = DateUtils.formatDateLastHour(DateUtils.getLaterHour(date));
                for (String meterId : meterIdClt) {
                    ColumnarData columnarData = new ColumnarData();
                    // al1的数组
                    List<BigDecimal> als = new ArrayList<>();
                    Map map = meterDao.findById(Long.valueOf(meterId));
                    meterRecords = meterMDao.findByDate(DateUtils.formatDateLastHour(DateUtils.getNowYMDH(date)), endTime,  Integer.valueOf(meterId));
                    if (meterRecords.size() > 0) {
                        for (int i = 0; i < meterRecords.size(); i++ ) {
                            MeterRecord meterRecord = meterRecords.get(i);
                            columnarData.setName(map.get("name").toString());
                            if (meterRecord == null || StringUtils.isEmpty(meterRecord.getUpperRow())) {
                                if (i == 0) {
                                    als.add(BigDecimal.ZERO);
                                } else {
                                    als.add(als.get(i - 1));
                                }
                            } else {
                                als.add(new BigDecimal(meterRecord.getUpperRow()));
                            }
                        }
//                        columnarData.setData(als);
                        columnarData.setType("bar");
                        columnarData.setLabel(new LabelOption());
                        list.add(columnarData);
                    }
                }
                break;
            case "2":
                // 后一天
                endTime = DateUtils.formatDateLastDay(DateUtils.getLaterDay(date));
                for (String meterId : meterIdClt) {
                    ColumnarData columnarData = new ColumnarData();
                    // al1的数组
                    List<BigDecimal> als = new ArrayList<>();
                    Map map = meterDao.findById(Long.valueOf(meterId));
                    meterRecords = meterHDao.findByDate(DateUtils.formatDateLastDay(DateUtils.getNowYMD(date)), endTime, Integer.valueOf(meterId));
                    if (meterRecords.size() > 0) {
                        for (int i = 0; i < meterRecords.size(); i++ ) {
                            MeterRecord meterRecord = meterRecords.get(i);
                            columnarData.setName(map.get("name").toString());
                            if (meterRecord == null || StringUtils.isEmpty(meterRecord.getUpperRow())) {
                                if (i == 0) {
                                    als.add(BigDecimal.ZERO);
                                } else {
                                    als.add(als.get(i - 1));
                                }
                            } else {
                                als.add(new BigDecimal(meterRecord.getUpperRow()));
                            }
                        }
//                        columnarData.setData(als);
                        columnarData.setType("bar");
                        columnarData.setLabel(new LabelOption());
                        list.add(columnarData);
                    }
                }

                break;
            case "3":
                // 后一月
                String[] dateStr = date.split("-");
                String year = dateStr[0];
                String laterMonth = "";
                if (dateStr.equals("12")) {
                    laterMonth = "01";
                    year  = String.valueOf(Integer.valueOf(year) + 1);
                } else {
                    laterMonth = String.valueOf(Integer.valueOf(dateStr[1]) + 1);
                }

                for (String meterId : meterIdClt) {
                    ColumnarData columnarData = new ColumnarData();
                    // al1的数组
                    List<BigDecimal> als = new ArrayList<>();
                    Map map = meterDao.findById(Long.valueOf(meterId));
                    if (laterMonth.length() < 2) {
                        laterMonth = "0" + laterMonth;
                    }
                    meterRecords = meterDDao.findByDate(date + "-01 00:00:00", date + "-31 00:00:00", Integer.valueOf(meterId));
                    if (meterRecords.size() > 0) {
                        for (int i = 0; i < meterRecords.size(); i++ ) {
                            MeterRecord meterRecord = meterRecords.get(i);
                            columnarData.setName(map.get("name").toString());
                            if (meterRecord == null || StringUtils.isEmpty(meterRecord.getUpperRow())) {
                                if (i == 0) {
                                    als.add(BigDecimal.ZERO);
                                } else {
                                    als.add(als.get(i - 1));
                                }
                            } else {
                                als.add(new BigDecimal(meterRecord.getUpperRow()));
                            }
                        }
//                        columnarData.setData(als);
                        columnarData.setType("bar");
                        columnarData.setLabel(new LabelOption());
                        list.add(columnarData);
                    }
                }
                break;
            case "4":
                // 后一年
                // map = meterDDao.findByDate(date, String.valueOf(Integer.valueOf(date) + 1));
                for (String meterId : meterIdClt) {
                    ColumnarData columnarData = new ColumnarData();
                    // al1的数组
                    List<BigDecimal> als = new ArrayList<>();
                    Map map = meterDao.findById(Long.valueOf(meterId));
                    meterRecords = meterYDao.findByDate(date + "-01-01 00:00:00",Integer.valueOf(date) + 1 + "" + "-01-01 00:00:00", Integer.valueOf(meterId));
                    if (meterRecords.size() > 0) {
                        for (int i = 0; i < meterRecords.size(); i++ ) {
                            MeterRecord meterRecord = meterRecords.get(i);
                            columnarData.setName(map.get("name").toString());
                            if (meterRecord == null || StringUtils.isEmpty(meterRecord.getUpperRow())) {
                                if (i == 0) {
                                    als.add(BigDecimal.ZERO);
                                } else {
                                    als.add(als.get(i - 1));
                                }
                            } else {
                                als.add(new BigDecimal(meterRecord.getUpperRow()));
                            }
                        }
//                        columnarData.setData(als);
                        columnarData.setType("bar");
                        columnarData.setLabel(new LabelOption());
                        list.add(columnarData);
                    }
                }
                break;
            default:
                // 前一分钟(获取年月日时分)
                // 后一分钟
                endTime = DateUtils.formatDateLastTime(DateUtils.getLaterMinute(date));

                for (String meterId : meterIdClt) {
                    ColumnarData columnarData = new ColumnarData();
                    // al1的数组
                    List<BigDecimal> als = new ArrayList<>();

                    Map map = meterDao.findById(Long.valueOf(meterId));
                    meterRecords = meterRecordDao.findByDate(date, endTime, Integer.valueOf(meterId));

                    if (meterRecords.size() > 0) {
                        for (int i = 0; i < meterRecords.size(); i++ ) {
                            MeterRecord meterRecord = meterRecords.get(i);
                            columnarData.setName(map.get("name").toString());
                            if (meterRecord == null || StringUtils.isEmpty(meterRecord.getUpperRow())) {
                                if (i == 0) {
                                    als.add(BigDecimal.ZERO);
                                } else {
                                    als.add(als.get(i - 1));
                                }
                            } else {
                                als.add(new BigDecimal(meterRecord.getUpperRow()));
                            }
                        }
//                        columnarData.setData(als);
                        columnarData.setType("bar");
                        columnarData.setLabel(new LabelOption());
                        list.add(columnarData);
                    }
                }
                break;
        }
        return list;
    }

    @Override
    public Long findByOnLine() {
        return meterDao.findByOnLine();
    }

    @Override
    public List<ExcelTemplate> findByDay(String type, String date,String laterDate, String meterIds) {
        return meterHDao.findByDay(type, date,laterDate, meterIds);
    }

    @Override
    public Map<String, List<ExcelTemplate>> groupLists(List<ExcelTemplate> lists) {
        Map<String, List<ExcelTemplate>> map = new HashMap<>();
        for (ExcelTemplate excelTemplate : lists ) {
            if (map.containsKey(excelTemplate.getName())) {
                map.get(excelTemplate.getName()).add(excelTemplate);
            } else {
                List<ExcelTemplate> list = new ArrayList<>();
                list.add(excelTemplate);
                map.put(excelTemplate.getName(), list);
            }
        }
        return map;
    }

    @Override
    public List<Meter> findAll() {
        return meterDao.findAlls();
    }
}
